package com.zfdang.touchhelper.fragment;

import static android.content.Context.WINDOW_SERVICE;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.preference.CheckBoxPreference;
import androidx.preference.EditTextPreference;
import androidx.preference.MultiSelectListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SeekBarPreference;

import com.aivin.adovertool.R;
import com.zfdang.touchhelper.bean.AppInformation;
import com.zfdang.touchhelper.bean.PackagePositionInfoBean;
import com.zfdang.touchhelper.bean.PackageWidgetInfoBean;
import com.zfdang.touchhelper.config.BaseConfig;
import com.zfdang.touchhelper.config.LyActionTypeConfig;
import com.zfdang.touchhelper.dialog.AppSelectDialogTool;
import com.zfdang.touchhelper.service.TouchHelperService;
import com.zfdang.touchhelper.tool.LyAppTool;
import com.zfdang.touchhelper.tool.LyNotifactionTool;
import com.zfdang.touchhelper.tool.LyPreferenceTool;
import com.zfdang.touchhelper.tool.SettingsTool;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ly-dengpw
 */
public class SettingsFragment extends PreferenceFragmentCompat {

    private final String TAG = getClass().getName();
    private Context context;
    LayoutInflater inflater;
    PackageManager packageManager;
    WindowManager winManager;
    MultiSelectListPreference activity_positions;
    MultiSelectListPreference activity_widgets;
    Map<String, Set<PackageWidgetInfoBean>> mapActivityWidgets;
    Map<String, PackagePositionInfoBean> mapActivityPositions;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.touch_helper_preference, rootKey);

        context = getContext();
        if (context == null) {
            throw new RuntimeException("context is null");
        }

        winManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        packageManager = context.getPackageManager();

        initPreferences();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 更新数据
        mapActivityWidgets = SettingsTool.getInstance().getPackageWidgets();
        updateMultiSelectListPreferenceEntries(activity_widgets, mapActivityWidgets.keySet());

        mapActivityPositions = SettingsTool.getInstance().getPackagePositions();
        updateMultiSelectListPreferenceEntries(activity_positions, mapActivityPositions.keySet());
    }


    private void initNotificationData() {
        CheckBoxPreference notification = findPreference("skip_ad_notification");
        if (notification == null) {
            return;
        }

        boolean needNotification = LyPreferenceTool.getInstance().getBoolean(BaseConfig.SKIP_AD_NOTIFICATION, true);
        notification.setChecked(needNotification);
        notification.setOnPreferenceChangeListener((preference, newValue) -> {
            LyPreferenceTool.getInstance().putBoolean(BaseConfig.SKIP_AD_NOTIFICATION, (Boolean) newValue);
            LyNotifactionTool.getInstance().showNotification(1,"中文消息" ,"开关状态="+newValue);
            return true;
        });
    }

    private void initDurationTime() {
        final SeekBarPreference duration = findPreference("skip_ad_duration");
        if (duration == null) {
            return;
        }

        duration.setMax(10);
        duration.setMin(1);
        duration.setUpdatesContinuously(true);
        int time = LyPreferenceTool.getInstance().getInt(BaseConfig.SKIP_AD_DURATION, 4);
        duration.setValue(time);

        duration.setOnPreferenceChangeListener((preference, newValue) -> {
            LyPreferenceTool.getInstance().putInt(BaseConfig.SKIP_AD_DURATION, (int) newValue);
            return true;
        });
    }

    private void initKeyWordConfig() {
        EditTextPreference textKeyWords = findPreference("setting_key_words");
        if (textKeyWords == null) {
            return;
        }
        textKeyWords.setText(SettingsTool.getInstance().getKeyWordsAsString());
        textKeyWords.setOnPreferenceChangeListener((preference, newValue) -> {
            LyPreferenceTool.getInstance().putString(BaseConfig.KEY_WORDS_LIST, newValue.toString());
            // 通知无障碍服务 关键字配置有更新
            TouchHelperService.dispatchAction(LyActionTypeConfig.ACTION_REFRESH_KEYWORDS);
            return true;
        });
    }


    private void initWidgetsData(){
        activity_widgets = findPreference("setting_activity_widgets");
        mapActivityWidgets = SettingsTool.getInstance().getPackageWidgets();
        updateMultiSelectListPreferenceEntries(activity_widgets, mapActivityWidgets.keySet());

        activity_widgets.setOnPreferenceChangeListener((preference, newValue) -> {
            HashSet<String> results = (HashSet<String>) newValue;

            Set<String> keys = new HashSet<>(mapActivityWidgets.keySet());
            for (String key : keys) {
                if (!results.contains(key)) {
                    mapActivityWidgets.remove(key);
                }
            }
            SettingsTool.getInstance().setPackageWidgets(mapActivityWidgets);
            updateMultiSelectListPreferenceEntries(activity_widgets, mapActivityWidgets.keySet());
            TouchHelperService.dispatchAction(LyActionTypeConfig.ACTION_REFRESH_CUSTOMIZED_ACTIVITY);
            return true;
        });
    }


    private void initPositionsConfig(){
        activity_positions =  findPreference("setting_activity_positions");
        mapActivityPositions = SettingsTool.getInstance().getPackagePositions();
        updateMultiSelectListPreferenceEntries(activity_positions, mapActivityPositions.keySet());

        activity_positions.setOnPreferenceChangeListener((preference, newValue) -> {
            HashSet<String> results = (HashSet<String>) newValue;
            Set<String> keys = new HashSet<>(mapActivityPositions.keySet());
            for (String key : keys) {
                if (!results.contains(key)) {
                    mapActivityPositions.remove(key);
                }
            }
            SettingsTool.getInstance().setPackagePositions(mapActivityPositions);
            updateMultiSelectListPreferenceEntries(activity_positions, mapActivityPositions.keySet());
            TouchHelperService.dispatchAction(LyActionTypeConfig.ACTION_REFRESH_CUSTOMIZED_ACTIVITY);

            return true;
        });
    }
    private void initWhiteAppListConfig() {
        Preference whitelist = findPreference("setting_whitelist");
        if (whitelist == null) {
            return;
        }
        whitelist.setOnPreferenceClickListener(preference -> {
            List<String> allAppPackageNames = LyAppTool.getAllAppPackageName(context);
            Set<String> pkgWhitelist = SettingsTool.getInstance().getWhitelistPackages();

            final ArrayList<AppInformation> listApp = new ArrayList<>();
            for (String pkgName : allAppPackageNames) {
                try {
                    ApplicationInfo info = packageManager.getApplicationInfo(pkgName, PackageManager.GET_META_DATA);
                    AppInformation appInfo = new AppInformation(pkgName, packageManager.getApplicationLabel(info).toString(), packageManager.getApplicationIcon(info));
                    appInfo.isChecked = pkgWhitelist.contains(pkgName);
                    listApp.add(appInfo);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }

            listApp.sort((bean1, bean2) -> {
                if (bean1.isChecked && !bean2.isChecked) {
                    return -11;
                } else if (!bean1.isChecked && bean2.isChecked) {
                    return 1;
                } else {
                    return bean1.applicationName.compareTo(bean2.applicationName);
                }
            });

            new AppSelectDialogTool().showDialog(context, listApp);
            return true;
        });
    }

    private void initPreferences() {
        initNotificationData();
        initDurationTime();
        initKeyWordConfig();
        initWhiteAppListConfig();

        Preference customizationView = findPreference("setting_activity_customization");
        if (customizationView != null) {
            customizationView.setOnPreferenceClickListener(preference -> {
                boolean result = TouchHelperService.dispatchAction(LyActionTypeConfig.ACTION_ACTIVITY_CUSTOMIZATION);
                if (!result) {
                    Toast.makeText(getContext(), "无障碍服务还未运行", Toast.LENGTH_SHORT).show();
                }
                return true;
            });
        }

        initWidgetsData();
        initPositionsConfig();
    }

    private void updateMultiSelectListPreferenceEntries(MultiSelectListPreference preference, Set<String> keys) {
        if (preference == null || keys == null) {
            return;
        }
        CharSequence[] entries = keys.toArray(new CharSequence[0]);
        // todo ,这三个方法有啥区别
        preference.setEntries(entries);
        preference.setEntryValues(entries);
        preference.setValues(keys);
    }
}